import passport from 'koa-passport'
import LocalStrategy from 'passport-local'
import UserModel from '../../dbs/models/users'

passport.use(new LocalStrategy(async function (username, password, done) {
  let where = {
    username
  }
  let result = await UserModel.findOne(where)
  if(result != null) {
    if(result.password === password) {
      return done(null, result)
    } else {
      return done(null, false, '密码错误')
    }
  } else {
    return done(null, false, '用户不存在')
  }
}))

// 序列化, 用户登录成功了，把用户数据存到session中
// 调用 ctx.login()会触发序列化操作
passport.serializeUser(function (user, done) {
  done(null, user)
})

//反序列化
// 在session如果存在 passport: {user: ''}会触发
passport.deserializeUser(function (user, done) {
  return done(null, user)
})

export default passport